#include "ImgProcessor.h"
#include "ui_mainwindow.h"

ImgProcessor::ImgProcessor(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("Easy Word");
    showWidget = new ShowWidget(this);
    setCentralWidget(showWidget);
    createActions();
    createMenus();
    createToolBars();

    if(img.load(tr("image.png")))
    {
        showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
    }
}

ImgProcessor::~ImgProcessor()
{
    delete ui;
}

void ImgProcessor::createActions()
{
    openFileAction = new QAction(QIcon("open.png"),tr("打开"),this);
    openFileAction->setShortcut(tr("Ctrl+O"));
    openFileAction->setStatusTip(tr("打开一个文件"));
//    connect(openFileAction,SIGNAL(triggered()),this,SLOT(ShowOpenFile()));
    connect(openFileAction,&QAction::triggered,this,&ImgProcessor::ShowOpenFile);
}

void ImgProcessor::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("文件"));
    fileMenu->addAction(openFileAction);
}

void ImgProcessor::createToolBars()
{

}

void ImgProcessor::loadFile(QString filename)
{
    printf("file name:%s\n",filename.data());
    QFile file(filename);
    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        QTextStream textStream(&file);
        while(!textStream.atEnd())
        {
            showWidget->text->append(textStream.readLine());
            printf("read line\n");
        }
    }
}

void ImgProcessor::ShowOpenFile()
{
    // fileName 是选中的文件的全路径名
    fileName = QFileDialog::getOpenFileName(this);
    if(!fileName.isEmpty())
    {
        cout << fileName.toStdString() << endl;
        if(showWidget->text->document()->isEmpty())
        {
            loadFile(fileName);
        }
    }
}

